/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.logs
{
	import flash.external.ExternalInterface;
	
	/**
	 * Sends the logs to the browser's console (if available).
	 * 
	 * Works on:
	 * <ul>
	 * <li>Firefox: needs <a href="http://getfirebug.com/">Firebug</a>.</li>
	 * <li>Internet Explorer, Opera:needs <a href="http://getfirebug.com/lite.html">Firebug Lite</a>.</li>
	 * <li>Safari: should work without any addition, although firebug lite can be used.</li>
	 * </ul>
	 */
	
	public class BrowserConsoleAppender implements IAppender
	{
		/**
		 * Creates a new BrowserConsoleAppender.
		 * 
		 * @param stringify If true, objects are dumped as their toString() representation.
		 * 
		 * Note: stringify could be required because some objects cannot be dumped and generate a stack overflow.
		 */
		
		private var stringify:Boolean;
		
		public function BrowserConsoleAppender(stringify:Boolean=false)
		{
			this.stringify = stringify;
		}

		public static function get available() : Boolean
		{
			return ExternalInterface.available;
		}

		/** @inheritDoc */
		public function append(msg:Array,level:int):void
		{
			if (!available)
				return;

			if (stringify)
				msg = [msg.join(' ')];
			else
				msg = msg.concat();
			
			msg.unshift('console.'+getMethodName(level));
			
			ExternalInterface.call.apply(null, msg);
		}
		
		private function getMethodName(num:int) : String
		{
			switch(num)
			{
				default:
				case Logger.LOG_LEVEL_NONE     : return 'log';
				case Logger.LOG_LEVEL_INFO     : return 'info';
				case Logger.LOG_LEVEL_DEBUG    : return 'debug';
				case Logger.LOG_LEVEL_WARNING  : return 'warn';
				case Logger.LOG_LEVEL_ERROR	   : return 'error';				
			}
		}		
	}
}
